import React, { useEffect, useMemo, useCallback, useRef } from 'react'
import './style.less'
import Step1 from './step1'
import Step2 from './step2'
import Step3 from './step3'
import { Tabs } from 'antd'
import type { TabsProps } from 'antd'
import { CloseCircleOutlined } from '@ant-design/icons'
import { useSearchParams, useNavigate } from 'react-router-dom'
import { useTypeStore } from '@/store/useBasicDataItem'
import { message } from '@hs-admin/utils'

const OperationBasicDataItemDetail: React.FC = () => {
  const [searchParams] = useSearchParams()
  const navigate = useNavigate()
  const id: string | null = searchParams?.get('id')
  const tabKey = useTypeStore((state) => state.tabKey)
  const setTabKey = useTypeStore((state) => state.setTabKey)
  const data_item_id = useTypeStore((state) => state.data_item_id)
  const step1Ref = useRef<any>(null)
  const step2Ref = useRef<any>(null)

  const goList = useCallback(() => {
    navigate(`/operationBasic/item`, {
      state: {
        params: {
          breadType: 'reset'
        }
      }
    })
  }, [navigate])
  const back = useCallback(() => {
    step1Ref.current && step1Ref.current.cancel()
    step2Ref.current && step2Ref.current.cancel()
    goList()
    setTabKey('1')
  }, [goList, setTabKey])

  const onChange = useCallback(
    (key: string) => {
      if ((key === '2' || key === '3') && !id && !data_item_id) {
        message.warning('请先保存数据项信息')
        return
      }
      setTabKey(key)
    },
    [setTabKey, id, data_item_id]
  )
  const items: TabsProps['items'] = useMemo(
    () => [
      {
        key: '1',
        label: '数据项信息',
        children: <Step1 ref={step1Ref} back={back} />
      },
      {
        key: '2',
        label: '核心字段',
        children: <Step2 ref={step2Ref} back={back} />
      },
      {
        key: '3',
        label: '样例数据',
        children: <Step3 back={back} />
      }
    ],
    [back]
  )

  useEffect(() => {
    const ele: any = items.find((item) => item.key === tabKey)
    setTabKey(ele.key)
    return () => {
      setTabKey('1')
    }
  }, [tabKey, items, setTabKey])

  return (
    <div className="DataItemDetail">
      <div className="top">
        <div className="top_title">
          <div>{id ? '编辑' : '新增'}数据项</div>
          <CloseCircleOutlined onClick={goList} />
        </div>
      </div>
      <div className="mid">
        <Tabs activeKey={tabKey} items={items} onChange={onChange} />
      </div>
    </div>
  )
}

export default OperationBasicDataItemDetail
